import { fileURLToPath, URL } from "node:url";
import { defineConfig } from "vite";
import postcsspxtoviewport from "postcss-px-to-viewport-8-plugin";
import vue from "@vitejs/plugin-vue";
import { VantResolver } from "@vant/auto-import-resolver";
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import UnoCSS from "unocss/vite";
import obfuscator from "javascript-obfuscator";
import { viteVConsole } from "vite-plugin-vconsole";
import path from "path";
import dayjs from 'dayjs'
const { obfuscate } = obfuscator;

const timeDir = dayjs().format('YYYYMMDDHHmm') 
const assetsPrefix = `assets-${timeDir}`

// https://vite.dev/config/
export default defineConfig(({ mode }) => ({
  build: {
    rollupOptions: {
      output: {
        // 所有静态资源统一打进一个带时间戳的目录
        assetFileNames: `${assetsPrefix}/[name].[hash][extname]`,
        chunkFileNames:  `${assetsPrefix}/[name].[hash].js`,
        entryFileNames:  `${assetsPrefix}/[name].[hash].js`,

        // 如果你仍然想把 keys.ts 单独保留
        manualChunks(id) {
          if (id.includes('src/config/keys.ts')) {
            return 'secret_keys'   // 会生成 secret_keys.[hash].js（也在 timeDir 里）
          }
        }
      }
    }
  },
  plugins: [
    viteVConsole({
      entry: [path.resolve("src/main.ts")], // 入口文件
      enabled: mode === "dev" || mode === "development", // 是否启用 vconsole
      config: {
        maxLogNumber: 1000,
      },
    }),
    AutoImport({
      resolvers: [VantResolver()],
    }),
    vue(),
    UnoCSS(),
    Components({
      resolvers: [VantResolver()],
      // 指定组件所在文件夹的位置，默认是src/components
      dirs: ["src/components"],
      // 配置type文件生成位置
      dts: "components.d.ts",
    }),
    {
      name: "obfuscate-keys-file",
      transform(code, id) {
        if (
          id.endsWith("src/config/keys.ts") ||
          id.includes("src\\config\\keys.ts")
        ) {
          try {
            const obfuscated = obfuscator.obfuscate(code, {
              compact: true,
              controlFlowFlattening: true,
              controlFlowFlatteningThreshold: 1,
              numbersToExpressions: true,
              simplify: true,
              stringArrayShuffle: true,
              splitStrings: true,
              stringArrayThreshold: 1,
              stringArray: true,
              stringArrayEncoding: ["base64"],
              stringArrayIndexShift: true,
              rotateStringArray: true,
              transformObjectKeys: true,
              unicodeEscapeSequence: true,
              renameGlobals: false,
              deadCodeInjection: true,
              deadCodeInjectionThreshold: 0.4,
            });
            return obfuscated.getObfuscatedCode();
          } catch (e) {
            console.error("Obfuscation failed:", e);
            return code; // 返回原始代码作为回退
          }
        }
        return code;
      },
    },
  ],
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `
        @use "@/assets/theme.scss" as *;
        `,
      },
    },
    postcss: {
      plugins: [
        postcsspxtoviewport({
          unitToConvert: "px", // 要转化的单位
          viewportWidth: 750, // UI设计稿的宽度
          unitPrecision: 6, // 转换后的精度，即小数点位数
          propList: ["*"], // 指定转换的css属性的单位，*代表全部css属性的单位都进行转换
          viewportUnit: "vmin", // 指定需要转换成的视窗单位，默认vw
          fontViewportUnit: "vmin", // 指定字体需要转换成的视窗单位，默认vw
          include: /\/src\//,
          selectorBlackList: [
            "ignore-",
            "image-item",
            "uploaded-images",
            "van-nav-bar__placeholder",
          ], // 指定不转换为视窗单位的类名，
          minPixelValue: 1, // 默认值1，小于或等于1px则不进行转换
          mediaQuery: false, // 是否在媒体查询的css代码中也进行转换，默认false
          replace: true, // 是否转换后直接更换属性值
          exclude: [/node_modules/], // 设置忽略文件，用正则做目录名匹配
          landscape: false, // 是否处理横屏情况
          landscapeUnit: "vmin", // 横屏转换单位
          landscapeWidth: 750, // 横屏时使用的视口宽度
        }),
        postcsspxtoviewport({
          viewportWidth: 375, // 设计稿的视窗宽度
          exclude: [/^(?!.*node_modules\/vant)/], // 对vant组件库单独处理
          viewportUnit: "vmin", // 指定需要转换成的视窗单位，默认vw
          fontViewportUnit: "vmin", // 指定字体需要转换成的视窗单位，默认vw
          landscape: false, // 是否处理横屏情况
          landscapeUnit: "vmin", // 横屏转换单位
          landscapeWidth: 375, // 横屏时使用的视口宽度
       }),
      ],
    },
  },
  resolve: {
    alias: {
      "@": fileURLToPath(new URL("./src", import.meta.url)),
    },
  },
  server: {
    // 设置 https 代理
    host: "0.0.0.0",
    proxy: {
      "/sdk": {
        target: "http://asdk.gaore.com",
        changeOrigin: true,
      },
    },
  },
}));
